<template>
  <a-drawer
    title="新增服务API"
    :maskClosable="false"
    width=950
    placement="right"
    :closable="false"
    @close="onClose"
    :visible="apiAddVisiable"
    style="height: calc(100% - 55px);overflow: auto;padding-bottom: 53px;">
    <a-form :form="form">
      <a-form-item label='服务：' v-bind="formItemLayout">
        <a-select
          mode="single"
          :allowClear="true"
          style="width: 100%"
          @change="handleServiceChange"
          v-decorator="['serviceSN',
           {rules: [
                    { required: true, message: '不能为空'}
          ]}]">
          <a-select-option v-for="type in serviceList" :key="type.key" :title="type.value">{{type.value}}</a-select-option>
        </a-select>
      </a-form-item>
      <a-form-item label='API名称' v-bind="formItemLayout">
        <a-input v-model="serviceApi.name"
                 v-decorator="['name',
                   {rules: [
                    { required: true, message: '不能为空'},
                    { max: 30, message: '长度不能超过30个字符'},
                    { validator: this.handleApiNameCheck }
                  ], validateTrigger: ['change', 'blur']}]"/>
      </a-form-item>
      <a-form-item label='请求方式' v-bind="formItemLayout">
        <a-input v-model="serviceApi.method"
                 v-decorator="['method',
                   {rules: [
                    { required: true, message: '不能为空'},
                    { max: 30, message: '长度不能超过30个字符'}
                  ]}]"/>
      </a-form-item>
      <a-form-item label='地址前缀' v-bind="formItemLayout">
        <a-input v-model="serviceApi.urlPrefix" placeholder="地址前缀（域名）"
                 v-decorator="['urlPrefix',
                   {rules: [
                    { required: true, message: '不能为空'},
                    { max: 60, message: '长度不能超过60个字符'}
                  ]}]"/>
      </a-form-item>
      <a-form-item label='接口地址' v-bind="formItemLayout">
        <a-input v-model="serviceApi.url"
                 v-decorator="['url',
                   {rules: [
                    { required: true, message: '不能为空'},
                    { max: 100, message: '长度不能超过100个字符'}
                  ]}]"/>
      </a-form-item>
      <a-form-item label='请求参数' v-bind="formItemLayout" style="position: relative">
        <div >
          <a-button class="editable-add-btn" @click="handleAdd">
            Add
          </a-button>
          <a-table bordered :data-source="dataSource" :columns="columns" :pagination="false" class="ntable" style="">
            <template slot="name" slot-scope="text, record">
              <editable-cell :text="text" @change="onCellNameChange(record.name, 'name', $event)" />
            </template>
            <template slot="type" slot-scope="text, record">
              <editable-cell :text="text" @change="onCellTypeChange(record.type, 'type', $event)" />
            </template>
            <template slot="required" slot-scope="text, record">
              <editable-cell :text="text" @change="onCellReqChange(record.required, 'required', $event)" />
            </template>
            <template slot="desc" slot-scope="text, record">
              <editable-cell :text="text" @change="onCellDescChange(record.desc, 'desc', $event)" />
            </template>
            <template slot="operation" slot-scope="text, record">
              <a-popconfirm
                v-if="dataSource.length"
                title="确定删除吗?"
                @confirm="() => onDelete(record.name)"
              >
                <a href="javascript:;">删除</a>
              </a-popconfirm>
            </template>
          </a-table>
        </div>
      </a-form-item>
      <a-form-item label='请求示例' v-bind="formItemLayout">
        <a-input v-model="serviceApi.requestExample"
                 v-decorator="['requestExample',
                   {rules: [
                    { required: true, message: '不能为空'},
                    { max: 100, message: '长度不能超过100个字符'}
                  ]}]"/>
      </a-form-item>
    </a-form>
    <a-form-item label='返回示例'  :labelCol="{span: 4}" :wrapperCol="{span:18}" >
      <!--<tinymce ref="richText"></tinymce>-->
      <a-textarea v-model="returnExample" :rows="15" />
    </a-form-item>
    <div class="drawer-bootom-button">
      <a-popconfirm title="确定放弃编辑？" @confirm="onClose" okText="确定" cancelText="取消">
        <a-button style="margin-right: .8rem">取消</a-button>
      </a-popconfirm>
      <a-button @click="handleSubmit" type="primary" :loading="loading">提交</a-button>
    </div>
  </a-drawer>
</template>
<script>
// import tinymce from '@/components/tinymce'
// window.tinymce.baseURL = window.projectUrl + '/static/tinymce' // 需要调用tinymce的组件中得加入这，不然会报错

const formItemLayout = {
  labelCol: { span: 4 },
  wrapperCol: { span: 18 }
}
const EditableCell = {
  template: `
      <div class="editable-cell">
        <div v-if="editable" class="editable-cell-input-wrapper">
          <a-input :value="value" @change="handleChange" @pressEnter="check" /><a-icon
            type="check"
            class="editable-cell-icon-check"
            @click="check"
          />
        </div>
        <div v-else class="editable-cell-text-wrapper">
          {{ value || ' ' }}
          <a-icon type="edit" class="editable-cell-icon" @click="edit" />
        </div>
      </div>
    `,
  props: {
    text: String
  },
  data () {
    return {
      value: this.text,
      editable: true
    }
  },
  methods: {
    handleChange (e) {
      const value = e.target.value
      this.value = value
    },
    check () {
      this.editable = false
      this.$emit('change', this.value)
    },
    edit () {
      this.editable = true
    }
  }
}
export default {
  name: 'ApiAdd',
  components: {
    /* tinymce, */
    EditableCell
  },
  props: {
    apiAddVisiable: {
      default: false
    },
    serviceList: {
      type: Array,
      default: () => []
    }
  },
  data () {
    return {
      loading: false,
      formItemLayout,
      form: this.$form.createForm(this),
      serviceApi: {},
      returnExample: '',
      dataSource: [],
      count: 0,
      columns: [
        {
          title: '名称',
          dataIndex: 'name',
          scopedSlots: { customRender: 'name' }
        },
        {
          title: '类型',
          dataIndex: 'type',
          scopedSlots: { customRender: 'type' }
        },
        {
          title: '必填',
          dataIndex: 'required',
          scopedSlots: { customRender: 'required' }
        },
        {
          title: '说明',
          dataIndex: 'desc',
          scopedSlots: { customRender: 'desc' }
        },
        {
          title: 'operation',
          dataIndex: 'operation',
          scopedSlots: { customRender: 'operation' }
        }
      ]
    }
  },
  mounted () {
    this.initService()
  },
  watch: {
    apiAddVisiable () {
      if (this.apiAddVisiable) {
        this.form.getFieldDecorator('serviceSN')
      }
    }
  },
  methods: {
    initService () {
      let aa = {}
      aa.ignoreName = ''
      this.$get('serviceInfo/api/tree', aa).then((r) => {
        let result = r.data
        result.forEach((res) => {
          this.serviceList.push({
            key: res.key,
            value: res.title
          })
        })
      })
    },
    handleServiceChange (key, option) {
      this.serviceApi.serviceSN = key || ''
    },
    onCellNameChange (name, dataIndex, value) {
      const dataSource = [...this.dataSource]
      const target = dataSource.find(item => item.name === name)
      if (target) {
        target[dataIndex] = value
        this.dataSource = dataSource
      }
    },
    onCellTypeChange (type, dataIndex, value) {
      const dataSource = [...this.dataSource]
      const target = dataSource.find(item => item.type === type)
      if (target) {
        target[dataIndex] = value
        this.dataSource = dataSource
      }
    },
    onCellReqChange (required, dataIndex, value) {
      const dataSource = [...this.dataSource]
      const target = dataSource.find(item => item.required === required)
      if (target) {
        target[dataIndex] = value
        this.dataSource = dataSource
      }
    },
    onCellDescChange (desc, dataIndex, value) {
      const dataSource = [...this.dataSource]
      const target = dataSource.find(item => item.desc === desc)
      if (target) {
        target[dataIndex] = value
        this.dataSource = dataSource
      }
    },
    onDelete (name) {
      const dataSource = [...this.dataSource]
      this.dataSource = dataSource.filter(item => item.name !== name)
    },
    handleAdd () {
      const { count, dataSource } = this
      const newData = {
        name: '',
        type: '',
        required: '',
        desc: ''
      }
      this.dataSource = [...dataSource, newData]
      this.count = count + 1
    },
    handleApiNameCheck (rule, value, callback) {
      let apiName = value.trim()
      if (apiName.length) {
        let serviceSn = this.serviceApi.serviceSN
        if (serviceSn === undefined || serviceSn === '') {
          this.validateStatus = 'error'
          callback(new Error('请先选择服务'))
        } else {
          this.$get(`serviceInfo/api/check/${apiName}/${serviceSn}`).then((r) => {
            if (r.data) {
              callback()
            } else {
              this.validateStatus = 'error'
              callback(new Error('抱歉，该API名称已存在'))
            }
          })
        }
      } else {
        callback()
      }
    },
    reset () {
      this.loading = false
      this.serviceApi = {}
      this.form.resetFields()
      this.dataSource = []
      this.count = 0
      // this.$refs.richText.setContent('')
      this.returnExample = ''
    },
    onClose () {
      this.reset()
      this.$emit('close')
    },
    handleSubmit () {
      this.form.validateFields((err, values) => {
        if (!err) {
          let serviceApi = this.form.getFieldsValue()
          // serviceApi.returnExample = this.$refs.richText.getContent()
          serviceApi.returnExample = this.returnExample
          serviceApi.serviceSN = this.serviceApi.serviceSN
          serviceApi.dataSource = JSON.stringify(this.dataSource)
          /* this.$post('serviceInfo/api', {
            ...serviceApi
          }).then(result => {
            if (result.data.code === '1') {
              this.reset()
              this.$emit('success')
            } else {
              this.$message.error('新增失败')
            }
          }).catch((data) => {
            this.loading = false
            this.$message.error('新增失败')
          }) */
        }
      })
    }
  }
}
</script>
<style>
  .editable-cell {
    position: relative;
  }

  .editable-cell-input-wrapper,
  .editable-cell-text-wrapper {
    padding-right: 24px;
  }

  .editable-cell-text-wrapper {
    padding: 5px 24px 5px 5px;
  }

  .editable-cell-icon,
  .editable-cell-icon-check {
    position: absolute;
    right: 0;
    width: 20px;
    cursor: pointer;
  }

  .editable-cell-icon {
    line-height: 18px;
    display: none;
  }

  .editable-cell-icon-check {
    line-height: 28px;
  }

  .editable-cell:hover .editable-cell-icon {
    display: inline-block;
  }

  .editable-cell-icon:hover,
  .editable-cell-icon-check:hover {
    color: #108ee9;
  }

  .editable-add-btn {
    margin-bottom: 8px;
  }
  .ant-table-bordered .ant-table-tbody > tr > td {
    padding: 2px;
    margin: 2px;
  }
</style>
